package com.licenta.fbApp.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwittit.client.facebook.FacebookConnect;
import com.gwittit.client.facebook.LoginCallback;
import com.gwittit.client.facebook.xfbml.FbLoginButton;
import com.gwittit.client.facebook.xfbml.Xfbml;

/**
 * Displays a rounded box ( firefox/safari ) with at facebook connect button.
 * And a link as backup in case the button is not rendered.
 */
public class LoginBox extends Composite {

  /**
 * @uml.property  name="outer"
 * @uml.associationEnd  multiplicity="(1 1)"
 */
private VerticalPanel outer = new VerticalPanel();

  // Callback that we define when setting up project.
  /**
 * @uml.property  name="loginButton"
 * @uml.associationEnd  multiplicity="(1 1)"
 */
private FbLoginButton loginButton = new FbLoginButton("facebookConnectLogin()");

  /**
 * @uml.property  name="loginLink"
 * @uml.associationEnd  multiplicity="(1 1)"
 */
private Anchor loginLink = new Anchor("don't see a button? Click here to login");

  /**
 * @uml.property  name="loginCallback"
 * @uml.associationEnd  
 */
private LoginCallback loginCallback;

  public void addLoginCallback(LoginCallback loginCallback) {
    this.loginCallback = loginCallback;
  }

  public LoginBox() {
    outer.setHeight("0"); // this will auto-fit it
    outer.getElement().setId("OuterRouter");
    // Login with the javascript api. GWT client doesnt render the
    // fb:login-button
    loginLink.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
        FacebookConnect.requireSession(new AsyncCallback<Boolean>() {
          public void onFailure(Throwable caught) {
            GWT.log("Require session failed: " + caught);
          }

          public void onSuccess(Boolean isLoggedIn) {
            if (loginCallback != null && isLoggedIn) {
              loginCallback.onLogin();
            }
          }
        });
      }

    });

    outer.getElement().setId("LoginBox");
    outer.add(loginButton);
    outer.add(loginLink);

    Xfbml.parse(outer);
    initWidget(outer);
  }

}
